<template>
  <div class="app-container">
      <!--搜索区-->
      <el-card class="filter-container" shadow="never">
          <div>
              <i class="el-icon-search"></i>
              <span>筛选搜索</span>
              <el-button style="float:right" type="primary" @click="handleQuery()" size="small">
                  查询搜索
              </el-button>
              <el-button style="float:right;margin-right: 15px" @click="resetQuery()" size="small">
                  重置
              </el-button>
              <div style="margin-top: 15px">
                  <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="140px">
                    <el-form-item label="输入搜索：">
                      <el-input v-model="queryParams.name" class="input-width" placeholder="请输入城区名称"/>
                    </el-form-item>
                  </el-form>
              </div>
          </div>
      </el-card>

      <!--操作按钮区-->
      <el-card class="operate-container" shadow="never">
          <i class="el-icon-tickets"></i>
          <span>数据列表</span>
          <el-button style="margin-left: 20px" type="primary" plain icon="el-icon-circle-plus" size="mini" @click="handleAdd" v-hasPermi="['basic:zone:create']">新增</el-button>
          <el-button type="success" plain icon="el-icon-upload" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['basic:zone:edit']">修改</el-button>
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['basic:zone:remove']">删除</el-button>
          <el-button type="warning" plain icon="el-icon-delete" size="mini" @click="handleExport" v-hasPermi="['basic:zone:export']">导出</el-button>
      </el-card>

      <!--数据列表区-->
      <div class="table-container">
          <el-table v-loading="loading" :data="zoneList" @selection-change="handleSelectionChange"
                    :default-expand-all="isExpandAll" row-key="zoneId"
                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}" border>
              <el-table-column prop="name" label="城区名称" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="状态" align="center">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.status"
                    :inactive-value="'1'"
                    :active-value="'0'"
                    active-text="显示"
                    inactive-text="隐藏"
                    @change="handleStatusChange(scope.$index, scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                      <el-button
                              size="mini"
                              type="text"
                              icon="el-icon-edit"
                              @click="handleUpdate(scope.row)"
                              v-hasPermi="['basic:zone:edit']"
                      >修改</el-button>
                      <el-button
                              size="mini"
                              type="text"
                              icon="el-icon-delete"
                              @click="handleDelete(scope.row)"
                              v-hasPermi="['basic:zone:remove']"
                      >删除</el-button>
                  </template>
              </el-table-column>
          </el-table>
      </div>

      <!--分页区-->

    <!-- 添加或修改城区信息表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属城市" prop="cityId">
          <el-select v-model="form.cityId" filterable placeholder="请选择所属城市" style="width: 100%">
            <el-option v-for="item in cityList" :key="item.cityId" :label="item.cityName" :value="item.cityId" />
          </el-select>
        </el-form-item>
        <el-form-item label="上级城区" prop="parentId">
          <treeselect v-model="form.parentId" :options="zoneOptions" :show-count="true" :normalizer="normalizer" placeholder="选择上级城区" />
        </el-form-item>
        <el-form-item label="城区名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入城区名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listZone, getZone, delZone, addZone, updateZone,updateStatus } from "@/api/basic/zone";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: {
    Treeselect,
    },
  name: "Zone",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 城区信息表表格数据
      zoneList: [],
      // 城市数据
      cityList: [],
      // 城区树
      zoneOptions: [],
      // 是否展开，默认全部不展开
      isExpandAll: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cityId: [
          { required: true, message: "所属城市不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "上级城区不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "城区名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询城区信息表列表 */
    getList() {
      this.loading = true;
      listZone(this.queryParams).then(response => {
        this.zoneList = this.handleTree(response.data, "zoneId");
        this.loading = false;
      });
    },
    /** 转换数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.zoneId,
        label: node.name,
        children: node.children
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        zoneId: null,
        cityId: null,
        parentId: null,
        status: "0",
        sortOrder: null,
        name: null,
        description: null,
        path: null,
        x: null,
        y: null,
        updatedTime: null,
        updatedBy: null,
        createdTime: null,
        createdBy: null,
        deleted: null,
        version: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.zoneId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查询城区下拉树结构 */
    getTreeselect() {
      listZone().then(response => {
        this.zoneOptions = [];
        const zone = { zoneId: 0, name: '作为一级城区', children: [] };
        zone.children = this.handleTree(response.data, "zoneId");
        this.zoneOptions.push(zone);
      });
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.zoneId) {
        this.form.parentId = row.zoneId;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      getZone().then(response => {
        this.cityList = response.data.cityList;
      })
      this.title = "添加城区";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getTreeselect();
      const zoneId = row.zoneId || this.ids
      getZone(zoneId).then(response => {
        this.form = response.data.zone;
        this.cityList = response.data.cityList;
        this.open = true;
        this.title = "修改城区信息表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.zoneId != null) {
            updateZone(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addZone(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const zoneIds = row.zoneId || this.ids;
      this.$modal.confirm('是否确认删除城区编号为"' + zoneIds + '"的数据项？').then(function() {
        return delZone(zoneIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basic/zone/export', {
        ...this.queryParams
      }, `zone_${new Date().getTime()}.xlsx`)
    },
    handleSizeChange(val) {
        this.queryParams.pageNum = 1;
        this.queryParams.pageSize = val;
        this.getList();
    },
    handleCurrentChange(val) {
        this.queryParams.pageNum = val;
        this.getList();
    },
    handleStatusChange(index, row) {
      this.$confirm('是否要修改该状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateStatus(row.roleId, {status: row.status}).then(response => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消修改'
        });
        this.getList();
      });
    },
  }
};
</script>
